/*
 * Copyright 2002-2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.framework;

import java.io.Closeable;

import org.springframework.beans.factory.Aware;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.Ordered;
import org.springframework.lang.Nullable;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;

/**
 * Base class with common functionality for proxy processors, in particular
 * ClassLoader management and the {@link #evaluateProxyInterfaces} algorithm.
 *
 * @author Juergen Hoeller
 * @since 4.1
 * @see AbstractAdvisingBeanPostProcessor
 * @see org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator
 */

/**
 1. 总结
 ProxyProcessorSupport 是Spring AOP中代理处理器的基类，提供通用功能

	 代理处理器基类 - 为Spring AOP中的各种代理处理器提供通用功能支持
	 ClassLoader管理 - 统一管理代理类生成所需的类加载器
	 接口评估算法 - 提供智能评估目标类接口并决定代理方式的核心算法

 2. 内部成员详解
 成员变量
	 order: int 类型，设置处理器的执行顺序，默认为 LOWEST_PRECEDENCE
	 proxyClassLoader: ClassLoader 类型，用于生成代理类的类加载器
	 classLoaderConfigured: boolean 类型，标记是否已配置类加载器
 方法
	 setOrder(int order): 设置处理器的执行顺序
	 getOrder(): 获取处理器的执行顺序
	 setProxyClassLoader(ClassLoader classLoader): 设置用于生成代理类的类加载器
	 getProxyClassLoader(): 获取配置的代理类加载器
	 setBeanClassLoader(ClassLoader classLoader): 实现 BeanClassLoaderAware 接口，设置Bean的类加载器
	 evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory): 评估并应用目标类的接口到 ProxyFactory
	 isConfigurationCallbackInterface(Class<?> ifc): 判断接口是否为容器回调接口
	 isInternalLanguageInterface(Class<?> ifc): 判断接口是否为内部语言接口

3 和其他接口和类之间的关系
 ProxyConfig (class)
 └── ProxyProcessorSupport (class)
	 ├── AbstractAdvisingBeanPostProcessor (abstract class)
	 │   └── AbstractBeanFactoryAwareAdvisingPostProcessor (abstract class)
	 │       └── PersistenceExceptionTranslationPostProcessor (class)
	 │       └── MethodValidationPostProcessor (class)
	 │       └── AsyncAnnotationBeanPostProcessor (class)
	 └── AbstractAutoProxyCreator (abstract class)
		 ├── AbstractAdvisorAutoProxyCreator (abstract class)
		 │   ├── DefaultAdvisorAutoProxyCreator (class)
		 │   └── InfrastructureAdvisorAutoProxyCreator (class)
		 │   └── AspectJAwareAdvisorAutoProxyCreator (class)
		 │  	 └── AnnotationAwareAspectJAutoProxyCreator (class)
         └── BeanNameAutoProxyCreator (class)


 相关类和接口说明
	 ProxyConfig: 父类，提供基础代理配置属性
	 Ordered: 实现此接口以控制处理器执行顺序
	 BeanClassLoaderAware: 实现此接口以获取Bean的类加载器
	 AopInfrastructureBean: 标记接口，标识AOP基础设施Bean
	 AbstractAdvisingBeanPostProcessor: 直接子类，用于为现有Bean添加通知
	 AbstractAutoProxyCreator: 直接子类，自动代理创建器的基类
	 ProxyFactory: 在evaluateProxyInterfaces方法中使用，用于实际创建代理
	 ProxyProcessorSupport为所有Spring AOP代理处理器提供统一的基础功能，特别是接口评估算法。

 4. 使用场景
	 AOP代理处理器开发: 作为开发自定义AOP代理处理器的基类
	 自动代理创建: 为自动代理创建器提供通用功能支持
	 Bean后置处理: 在Bean后置处理器中处理代理创建逻辑
	 接口评估: 需要根据目标类的接口决定代理方式的场景
 5. 实际代码应用示例
 ===================案例1  自定义Bean后置处理器
 public class CustomBeanPostProcessor extends ProxyProcessorSupport  implements BeanPostProcessor {
	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		// 检查是否需要代理
		if (shouldProxy(bean)) {
			 ProxyFactory proxyFactory = new ProxyFactory(bean);

			// 使用父类方法评估接口
			evaluateProxyInterfaces(bean.getClass(), proxyFactory);

			// 添加自定义拦截器
			proxyFactory.addAdvice(new CustomMethodInterceptor());

			// 创建代理
			return proxyFactory.getProxy(getProxyClassLoader());
		}
		return bean;
	}

	private boolean shouldProxy(Object bean) {
		// 自定义代理条件判断逻辑
		return bean.getClass().isAnnotationPresent(EnableCustomProxy.class);
	}
}
===========案例2  扩展自动代理创建器

 public class CustomAutoProxyCreator extends ProxyProcessorSupport {
	 protected Object createProxy(Class<?> beanClass, String beanName, Object specificInterceptors) {
		 ProxyFactory proxyFactory = new ProxyFactory();

		 // 设置代理配置
		 proxyFactory.copyFrom(this);

		 // 评估并设置代理接口
		 evaluateProxyInterfaces(beanClass, proxyFactory);

		 // 添加拦截器
		 proxyFactory.addAdvisors((Advisor[]) specificInterceptors);

		 // 创建代理
		 return proxyFactory.getProxy(getProxyClassLoader());
	 }
 }

 ===========案例3  代理接口评估算法
 // 目标类实现多个接口
 public class MyService implements UserService, InitializingBean {
 // 实现方法...
 }

 // 使用evaluateProxyInterfaces方法
 ProxyFactory proxyFactory = new ProxyFactory();
 ProxyProcessorSupport support = new ProxyProcessorSupport();

 // 会自动评估接口，排除InitializingBean等回调接口
 support.evaluateProxyInterfaces(MyService.class, proxyFactory);

 // 结果：只会代理UserService接口，不会代理InitializingBean



 */
@SuppressWarnings("serial")
public class ProxyProcessorSupport extends ProxyConfig implements Ordered, BeanClassLoaderAware, AopInfrastructureBean {

	/**
	 * This should run after all other processors, so that it can just add
	 * an advisor to existing proxies rather than double-proxy.
	 */
	private int order = Ordered.LOWEST_PRECEDENCE;

	@Nullable
	private ClassLoader proxyClassLoader = ClassUtils.getDefaultClassLoader();

	private boolean classLoaderConfigured = false;


	/**
	 * Set the ordering which will apply to this processor's implementation
	 * of {@link Ordered}, used when applying multiple processors.
	 * <p>The default value is {@code Ordered.LOWEST_PRECEDENCE}, meaning non-ordered.
	 * @param order the ordering value
	 */
	public void setOrder(int order) {
		this.order = order;
	}

	@Override
	public int getOrder() {
		return this.order;
	}

	/**
	 * Set the ClassLoader to generate the proxy class in.
	 * <p>Default is the bean ClassLoader, i.e. the ClassLoader used by the containing
	 * {@link org.springframework.beans.factory.BeanFactory} for loading all bean classes.
	 * This can be overridden here for specific proxies.
	 */
	public void setProxyClassLoader(@Nullable ClassLoader classLoader) {
		this.proxyClassLoader = classLoader;
		this.classLoaderConfigured = (classLoader != null);
	}

	/**
	 * Return the configured proxy ClassLoader for this processor.
	 */
	@Nullable
	protected ClassLoader getProxyClassLoader() {
		return this.proxyClassLoader;
	}

	@Override
	public void setBeanClassLoader(ClassLoader classLoader) {
		if (!this.classLoaderConfigured) {
			this.proxyClassLoader = classLoader;
		}
	}


	/**
	 * Check the interfaces on the given bean class and apply them to the {@link ProxyFactory},
	 * if appropriate.
	 * <p>Calls {@link #isConfigurationCallbackInterface} and {@link #isInternalLanguageInterface}
	 * to filter for reasonable proxy interfaces, falling back to a target-class proxy otherwise.
	 * @param beanClass the class of the bean
	 * @param proxyFactory the ProxyFactory for the bean
	 */
	protected void evaluateProxyInterfaces(Class<?> beanClass, ProxyFactory proxyFactory) {
		Class<?>[] targetInterfaces = ClassUtils.getAllInterfacesForClass(beanClass, getProxyClassLoader());
		boolean hasReasonableProxyInterface = false;
		for (Class<?> ifc : targetInterfaces) {
			if (!isConfigurationCallbackInterface(ifc) && !isInternalLanguageInterface(ifc) &&
					ifc.getMethods().length > 0) {
				hasReasonableProxyInterface = true;
				break;
			}
		}
		if (hasReasonableProxyInterface) {
			// Must allow for introductions; can't just set interfaces to the target's interfaces only.
			for (Class<?> ifc : targetInterfaces) {
				proxyFactory.addInterface(ifc);
			}
		}
		else {
			proxyFactory.setProxyTargetClass(true);
		}
	}

	/**
	 * Determine whether the given interface is just a container callback and
	 * therefore not to be considered as a reasonable proxy interface.
	 * <p>If no reasonable proxy interface is found for a given bean, it will get
	 * proxied with its full target class, assuming that as the user's intention.
	 * @param ifc the interface to check
	 * @return whether the given interface is just a container callback
	 */
	protected boolean isConfigurationCallbackInterface(Class<?> ifc) {
		return (InitializingBean.class == ifc || DisposableBean.class == ifc || Closeable.class == ifc ||
				AutoCloseable.class == ifc || ObjectUtils.containsElement(ifc.getInterfaces(), Aware.class));
	}

	/**
	 * Determine whether the given interface is a well-known internal language interface
	 * and therefore not to be considered as a reasonable proxy interface.
	 * <p>If no reasonable proxy interface is found for a given bean, it will get
	 * proxied with its full target class, assuming that as the user's intention.
	 * @param ifc the interface to check
	 * @return whether the given interface is an internal language interface
	 */
	protected boolean isInternalLanguageInterface(Class<?> ifc) {
		return (ifc.getName().equals("groovy.lang.GroovyObject") ||
				ifc.getName().endsWith(".cglib.proxy.Factory") ||
				ifc.getName().endsWith(".bytebuddy.MockAccess"));
	}

}
